<?php

namespace Partner\Controller;

use Utuo\BackgroundController;
use Utuo\Region;
use Utuo\Phpass;

class CustomerController extends BackgroundController {
	
	// 初始化
	public function _initialize() {
		$this->setControllerTitle('客户管理');
		$this->setActionTitle(array(
				'index' => '客户列表',
				'add' => '添加客户',
				'modify' => '修改客户',
				'recycle' => '回收站' ,
				'setRole'=>'分配权限'
		));
		$this->setActionNav(array(
				'index',
				'add',
				'recycle' 
		));
	}
	
	public function loginAction() {
		$id = I("id", 0, "intval");
		$cid = I("cid", 0, "intval");
		$cid and $id = M("CustomerAdmin")->where('cid=%d and is_super=1', $cid)->getField('id');
		$condition = array("a.id" => $id);
		$customer = M("CustomerAdmin a")->join("__CUSTOMER__ b on a.cid=b.id", "LEFT")->where($condition)->field('a.*,b.partner')->find();
		$_SESSION["_my_"] = array(
				"userid" => $customer['id'],
				"id" => $cid ? $cid : $customer['cid'],
				"name" => $customer['name']."(".session("name").")",
				"pid" => $customer['partner'],
				self::LOGIN_TIME => time(),
				self::LAST_ACTIVE => time(),
				self::IS_LOGINED => true,
		);
		$_SESSION["_my_"]["sessionKeys"] = serialize(array_keys($_SESSION["_my_"]));
		$this->success("", U("My/Index/index"));
	}
	
	
	// 客户列表
	public function indexAction() {
		$this->getList(0);
	}
	
	// recycle of customer to display
	public function recycleAction() {
		$this->getList(1);
	}
	
	/**
	 * display the customer list
	 * 
	 * @param unknown $is_deleted 是否已删除
	 */
	private function getList($is_deleted) {
		$p = I("p", 1, 'intval');
		$pageSize = 10;
		/*查询条件*/
		$name = I('name', "");
		/*有条件查询*/
		$condition = array(
				"this0.is_deleted" => $is_deleted,
				"this0.partner" => $this->aid ,
		);
		$param = array();
		$name and $condition['this0.name'] = array('like', "%$name%") and $param['name'] = $name;
		/*搜索*/
		$customerListSql = M()->table("__CUSTOMER__ this0")->join('LEFT JOIN __CN_PROVINCE__ this1 on this0.province=this1.code')->join('LEFT JOIN __CN_CITY__ this2 on this0.city=this2.code')->join('LEFT JOIN __CN_AREA__ this3 on this0.area=this3.code')->field("this0.*,this1.name as provinceName,this2.name as cityName,this3.name as areaName")->select(false);
		$customerLists = M()->table($customerListSql . " this0")->where($condition)->limit($pageSize)->page($p)->order('id desc')->select();
		$count = M()->table($customerListSql . " this0")->where($condition)->count();
		$this->assign("customerLists", $customerLists);
		$this->assign("param", $param);
		$this->showPage($count, $pageSize);
		$this->display();
	}
	
	// to custormer's add page
	public function addAction() {
		$partnerLists = M("Partner")->where('is_deleted=0')->getField('id,name');
		$this->partnerOptions = $this->getOption($partnerLists, null, '==请选择合作商==');
		$this->provinceOptions = $this->getOption(Region::getProvinceList(), null, '==请选择省份==');
		$this->cityOptions = $this->getOption(array(), null, '==请选择城市==');
		$this->areaOptions = $this->getOption(array(), null, '==请选择地区==');
		$this->display();
	}
	
	// add post
	public function addPostAction() {
		$d = D("customer");
		if ($d->create()) {
			$dd = clone  $d;
			$d->partner = $this->aid;
			if (!empty($d->password)) {
				$d->password = Phpass::hash($d->password);
			} else {
				$this->ajaxError("密码不能为空!");
			}
			if ( $cid = $d->add() ) {
				false !== M("CustomerAdmin")->add( array(
						'cid' => $cid,
						'name' => $dd->name,
						'email' => $dd->email,
						'password' => $dd->password,
						'last_login_time' => 0,
						'last_login_ip' => '',
						'login_count' => 0,
						'is_role' => 0,
						'is_super' => 1,
				)) and $this->ajaxSuccess();
			} else {
				$this->ajaxError();
			}
		} else {
			$this->ajaxError($d->getError());
		}
	}
	
	// redirect to modiy page
	public function modifyAction() {
		$customer = $this->getOneById("customer");
		if ($customer) {
			$this->checkAdmin($customer['partner']);
			$partnerLists = M("Partner")->where('is_deleted=0')->getField('id,name');
			$customer['partnerOptions'] = $this->getOption($partnerLists, $customer['partner'], '==请选择合作商==');
			$customer['provinceOptions'] = $this->getOption(Region::getProvinceList(), $customer['province'], '==请选择省份==');
			$customer['cityOptions'] = $this->getOption(Region::getCityListByProvince($customer['province']), $customer['city'], '==请选择城市==');
			$customer['areaOptions'] = $this->getOption(Region::getAreaListByCity($customer['city']), $customer['area'], '==请选择地区==');
			$this->assign("customer", $customer);
			$this->display();
		} else {
			$this->error('客户不存在');
		}
	}
	
	// modify customer and execute
	public function modifyPostAction() {
		$d = D("Customer");
		if ($d->create()) {
			$this->checkAdmin(null, $d, "partner");
			$d->partner = $this->aid;
			if (empty($d->password)) {
				unset($d->password);
			} else {
				$d->password = Phpass::hash($d->password);
			}
			if (false !== $d->save()) {
				$this->ajaxSuccess();
			} else {
				$this->ajaxError();
			}
		} else {
			$this->ajaxError($d->getError());
		}
	}
	
	// remove customer
	public function removePostAction() {
		$this->checkAdmin(null, M("Customer"), "partner");
		$this->ajaxRemove();
	}
	
	// restore customer
	public function restorePostAction() {
		$this->checkAdmin(null, M("Customer"), "partner");
		$this->ajaxRestore();
	}
	
	// delete customer;
	public function deletePostAction() {
		$this->checkAdmin(null, M("Customer"), "partner");
		$this->ajaxDelete();
	}
	
	// status update
	public function setStatusPostAction() {
		$id = I("id", 0, "intval");
		$status = I("status", 0, "intval");
		$customer = M("customer");
		if ($customer->where("id={$id}")->setField("status", 1 - $status)) {
			$this->ajaxSuccess();
		} else {
			$this->ajaxError($customer->getError());
		}
	}
	
	// 获取城市
	public function getCityPostAction() {
		echo $this->getOption(Region::getCityListByProvince(I('code')), '', '==请选择城市==');
	}
	
	// 获取地区
	public function getAreaPostAction() {
		echo $this->getOption(Region::getAreaListByCity(I('code')), '', '==请选择地区==');
	}
	
	public function setRoleAction($cid) {
		$role=M('Role')->where('is_deleted=%d and partner_id=%d',0,$this->aid)->getField('id,remark');
		$roleCus=M('RoleCustomer')->where('customer_id=%d',$cid)->getField("role_id",true);
		$fid=M('customer')->where('id='.$cid)->getField("fid");
		if($fid && !$roleCus)
		{
			$roleArray=M('RoleCustomer')->where('customer_id=%d',$fid)->getField("role_id",true);
			$array=array();
			foreach ($roleArray as $v)
			{
				$array[]=array('role_id'=>$v,'customer_id'=>$cid);
			}
			M('RoleCustomer')->addAll($array);
			$cid=$fid;
		}
		$roleids=D('RoleCustomer')->where('customer_id=%d',$cid)->getField("role_id",true);
		
		$data['roleCheckbox']=\Utuo\Form::makeCheckbox($role,$roleids,'role_id[]');
		$data['cid']=$cid;
		$this->assign("data",$data);
		$this->display();
	}
	
	public function saveRoleAction(){
		$cid=I('cid');
		$role_ids=I('role_id');
		D('RoleCustomer')->where('customer_id=%d',$cid)->delete();
		if(is_array($role_ids))
		{
			foreach ($role_ids as $v)
			{
				D('RoleCustomer')->add(array(
				'customer_id'=>$cid,
				'role_id'=>$v
				));
	
			}
			$this->ajaxSuccess();
		}
		$this->ajaxError();
	
	}
	
	/**
	 * 是否开启角色分配
	 * @param unknown $cid
	 * @param unknown $isrole
	 */
	public function isRoleAction($cid,$isrole)
	{
		M('Customer')->where('id=%d',$cid)->setField("is_role",$isrole)?$this->ajaxSuccess():$this->ajaxError();
	}
}